# docstring
__version__ = "$Revision: 44 $"
# $Id: models.py 44 2008-08-02 22:33:06Z AxisOfEntropy $

from django.db import models
from django.contrib import admin

from countries.models import Country #For internationalization
from django.utils.translation import ugettext as _ #For internationalization

from django.conf import settings

# Create your models here.

EUROPASS_GENDER_CHOICES = (
    ('M', _('Male')),
    ('F', _('Female')),
    ('NA', _('Do not indicate')),
)

EUROPASS_LANGENUM = (
    ('mother', _('Mother tongue(s)')),
    ('foreign', _('Other language(s)')),
)

EUROPASS_LANGLEVEL = (
    ('a1', 'A1'),
    ('a2', 'A2'),
    ('b1', 'B1'),
    ('b2', 'B2'),
    ('c1', 'C1'),
    ('c2', 'C2'),
)

class Photo(models.Model):
    photo = models.ImageField(_("photograph"), max_length=128, upload_to="photo")
    #learner_information = models.ForeignKey(LearnerInformation, edit_inline=models.TABULAR, num_in_admin=1)

    def base64(self):
        """Return the contents of the photo file as a base64 encoded string."""
        try:
            f = open(self.get_photo_filename(), 'r')
            raw_image = f.read(10485760)
            f.close()
        except IOError:
            # If we can't load the file, return an empty string and hope everything upstream can deal with that.
            return ''
        else:
            from base64 import b64encode
            return b64encode(raw_image)

    def phototype(self):
        """Return the image file type.
            For now, this guesses by the file extension, since the Europass
            parser doesn't seem to care very much."""
        return self.photo.split('.')[-1].upper()

class PhotoAdmin(admin.ModelAdmin):
    pass

admin.site.register(Photo, PhotoAdmin)

class LearnerInformation(models.Model):
    """This class forms the root XML element.  Most other models will have foreign keys to this."""
    #refactored to be an actual locale, given from facebook #locale = models.ForeignKey(Country, related_name='learnerinformation_locale_set')
    locale = models.CharField(max_length=5, choices=settings.LANGUAGES, default="en_GB", help_text=_("This is the language that your resume will be displayed in."))

    #identification
    firstname = models.CharField(_("first name(s)"), max_length=256, core=True)
    lastname = models.CharField(_("surname(s)"), max_length=256, core=True)
    #factored out photo to its own object #photo = models.ImageField(max_length=128, upload_to="photo", blank=True)
    photo = models.OneToOneField(Photo, null=True, blank=True)
    application = models.CharField(_("desired employment / occupational field"), max_length=1024, blank=True)
    
    #addressinfo
    addressLine1 = models.CharField(_("address line 1"), max_length=256, blank=True)
    addressLine2 = models.CharField(_("address line 2"), max_length=256, blank=True)
    municipality = models.CharField(_("city"), max_length=64, blank=True)
    postalCode = models.CharField(_("postal code"), max_length=32, blank=True)
    country = models.ForeignKey(Country, null=True, blank=True, related_name='learnerinformation_country_set')
    
    #contactinfo
    telephone = models.CharField(_("telephone(s)"), max_length=64, blank=True)
    fax = models.CharField(_("fax"), max_length=64, blank=True)
    mobile = models.CharField(_("mobile"), max_length=64, blank=True)
    email = models.EmailField(_("e-mail(s)"), blank=True)
    web = models.URLField(_("website"), blank=True)

    #demographics
    birthdate = models.DateField(_("birthdate"), blank=True, null=True)
    gender = models.CharField(_("gender"), max_length=2, choices=EUROPASS_GENDER_CHOICES, blank=True)
    
    #skilllist
    skill_social = models.TextField(_("social skills and competences"), max_length=4096, blank=True)
    skill_organizational = models.TextField(_("organisational skills and competences"), max_length=4096, blank=True)
    skill_technical = models.TextField(_("technical skills and competences"), max_length=4096, blank=True)
    skill_computer = models.TextField(_("computer skills and competences"), max_length=4096, blank=True)
    skill_artistic = models.TextField(_("artistic skills and competences"), max_length=4096, blank=True)
    skill_other = models.TextField(_("other skills and competences"), max_length=4096, blank=True)
    skill_driving = models.TextField(_("driving licence(s)"), max_length=4096, blank=True)

    #miscellaneous
    additional = models.TextField(_("additional information"), max_length=4096, blank=True)
    annexes = models.TextField(_("annexes"), max_length=4096, blank=True, help_text=_("If you have any attachments, describe them here."))

    #Extra properties and methods:
    def count_mother_languages(self):
        "Returns the number of languages of type 'mother' that are associated with this object."
        return self.language_set.filter(type="mother").count()

    def count_foreign_languages(self):
        "Returns the number of languages of type 'foreign' that are associate with this object."
        return self.language_set.filter(type="foreign").count()

    def mother_language_set(self):
        "Returns a queryset like self.language_set but filtered for only foreign languages."
        return self.language_set.filter(type="mother")

    def foreign_language_set(self):
        "Returns a queryset like self.language_set but filtered for only foreign languages."
        return self.language_set.filter(type="foreign")

    def __unicode__(self):
        return u'%s - %s - %s %s' % (self.id, self.locale, self.firstname, self.lastname)

class LearnerInformationAdmin(admin.ModelAdmin):
    pass

admin.site.register(LearnerInformation, LearnerInformationAdmin)

class Nationality(models.Model):
    demographics = models.ForeignKey(LearnerInformation, edit_inline=models.STACKED, num_in_admin=1)
    label = models.CharField(_("nationality"), max_length=32, core=True)
    code = models.ForeignKey(Country, core=True, null=True)

    def __unicode__(self):
        return u'%s - %s' % (self.code, self.label)

class NationalityAdmin(admin.ModelAdmin):
    pass

admin.site.register(Nationality, NationalityAdmin)

class WorkExperience(models.Model):
    employer = models.CharField(_("name and address of employer"), max_length=1024, blank=True)
    position = models.CharField(_("occupation or position held"), max_length=1024, blank=True, core=True)
    activities = models.CharField(_("main activities and responsibilities"), max_length=1024, blank=True)
    sector = models.CharField(_("type of business or sector"), max_length=1024, blank=True)
    period_from = models.DateField(_("from"), blank=True, null=True)
    period_to = models.DateField(_("to"), blank=True, null=True)

    learner_information = models.ForeignKey(LearnerInformation)
    
    #display_order = models.SmallIntegerField(core=True)

    def __unicode__(self):
        return u'%s - %s' % (self.learner_information, self.id)

class WorkExperienceAdmin(admin.ModelAdmin):
    pass

admin.site.register(WorkExperience, WorkExperienceAdmin)

class Education(models.Model):
    organization = models.CharField(_("name and type of organsation providing education and training"), max_length=1024, blank=True)
    skills = models.CharField(_("prinicpal subjects / occupational skills covered"), max_length=1024, blank=True)
    title = models.CharField(_("title of qualification awarded"), max_length=1024, blank=True, core=True)
    level = models.CharField(_("level in national or international classification"), max_length=1024, blank=True)
    period_from = models.DateField(_("from"), blank=True, null=True)
    period_to = models.DateField(_("to"), blank=True, null=True)

    learner_information = models.ForeignKey(LearnerInformation)

    def __unicode__(self):
        return u'%s - %s' % (self.learner_information, self.id)

class EducationAdmin(admin.ModelAdmin):
    pass

admin.site.register(Education, EducationAdmin)
    
class Language(models.Model):
    code = models.CharField(max_length=2)
    label = models.CharField(_("language"), max_length=256)
    type = models.CharField(max_length=16, core=True, choices=EUROPASS_LANGENUM)
    level_listening = models.CharField(_("listening"), max_length=2, blank=True, choices=EUROPASS_LANGLEVEL)
    level_reading = models.CharField(_("reading"), max_length=2, blank=True, choices=EUROPASS_LANGLEVEL)
    level_spokeninteraction = models.CharField(_("spoken interaction"), max_length=2, blank=True, choices=EUROPASS_LANGLEVEL)
    level_spokenproduction = models.CharField(_("spoken production"), max_length=2, blank=True, choices=EUROPASS_LANGLEVEL)
    level_writing = models.CharField(_("writing"), max_length=2, blank=True, choices=EUROPASS_LANGLEVEL)
        
    learner_information = models.ForeignKey(LearnerInformation)
    
    #probably a better way to do this #display_order = models.SmallIntegerField(core=True)
    
    def __unicode__(self):
        return u'%s - %s' % (self.code, self.label)

class LanguageAdmin(admin.ModelAdmin):
    pass

admin.site.register(Language, LanguageAdmin)

# class Experience(models.Model):
    # # These seem to be not yet implemented by Europass
    # period_from = models.DateField(_("from"), blank=True, null=True)
    # period_to = models.DateField(_("to"), blank=True, null=True)
    # description = models.CharField(_("description"), max_length=4096, blank=True, core=True)
    
    # learner_information = models.ForeignKey(LearnerInformation, ) #edit_inline=models.STACKED, num_in_admin=2)
    
    # class Admin:
        # pass

# class Miscellaneous(models.Model):
    # # Not yet implemented by Europass
    # type = models.CharField(max_length=16, choices=EUROPASS_MISCENUM, core=True)
    # misc = models.CharField(max_length=4096, blank=True)
    
    # learner_information = models.ForeignKey(LearnerInformation, edit_inline=models.TABULAR, num_in_admin=2)
    
    # class Admin:
        # pass

# class Skill(models.Model):
    # # Not yet implemented by Europass
    # type = models.CharField(max_length=16, choices=EUROPASS_SKILLENUM, core=True)
    # skill = models.CharField(max_length=4096)
    
    # learner_information = models.ForeignKey(LearnerInformation, edit_inline=models.TABULAR, num_in_admin=5)
    
    # class Admin:
        # pass

# class Diploma(models.Model):
    # # These seem to be not yet implemented.
    # title = models.CharField(max_length=1024)
    # awardingBody = models.CharField(max_length=1024)
    # date = models.DateField()
    # level = models.CharField(max_length=1024)
    
    # language = models.ForeignKey(Language)
    
    # class Admin:
        # pass